package com.vlyman.shiro.jwt;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.vlyman.consts.UriConsts;
import com.vlyman.rtn.SystemRtn;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：
 *  jwt过滤器
 * @author chenjs
 * @date 2019/1/8 17:00
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 方法描述：
     *   检测Header里面是否包含Authorization字段，有就进行Token登录认证授权
     *  @author chenjs
     *  @param request
     *  @param response
     *  @return boolean
     *  @date 2019/1/9 09:42
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        // 拿到当前Header中Authorization的AccessToken(Shiro中getAuthzHeader方法已经实现)
        String token = this.getAuthzHeader(request);
        return token != null;
    }

    /**
     * 方法描述：
     *   进行AccessToken登录认证授权
     *  @author chenjs
     *  @param request
     *  @param response
     *  @return boolean
     *  @date 2019/1/9 10:18
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        JwtToken token = new JwtToken(this.getAuthzHeader(request));
        // 提交给Realm进行认证，如果错误他会抛出异常并被捕获
        this.getSubject(request, response).login(token);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     * 方法描述：
     *   重写父类方法，将executeLogin方法去除，否则会循环调用doGetAuthenticationInfo方法
     *  @author chenjs
     *  @param request
     *  @param response
     *  @return boolean
     *  @date 2019/1/9 10:37
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        this.sendChallenge(request, response);
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 判断用户是否想要登入
        int code = SystemRtn.TOKEN_MISSING.getCode();
        if (this.isLoginAttempt(request, response)){
            try {
                // 进行Shiro的登录操作
                this.executeLogin(request, response);
                return true;
            } catch (AccountException e) {
                log.error(SystemRtn.getRtnByCode(e.getMessage()).getMsg(), e);
                code = Integer.valueOf(e.getMessage());
            } catch (Exception e) {
                log.error(SystemRtn.LOGIN_ERROR.getMsg(), e);
                code = SystemRtn.LOGIN_ERROR.getCode();
            }
        }
        try {
            request.getRequestDispatcher(UriConsts.SYSBASE_ERROR_PREFIX+"/system/"+code).forward(request, response);
        } catch (Exception e) {
            log.error("转发至error控制器出错！", e);
        }
        return false;
    }

    /**
     * 方法描述：
     *   对跨域提供支持
     *  @author chenjs
     *  @param request
     *  @param response
     *  @return boolean
     *  @date 2019/1/9 10:16
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
